package com.biwei.app.wrap.exception;

import com.biwei.app.wrap.bean.Result2;
import com.biwei.app.wrap.util.JsonUtil;
import feign.FeignException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public void exceptionHandler(Exception e, HttpServletResponse response)  throws IOException {
        response.setStatus(500);
        log.error("Exception", e);
    }

    @ExceptionHandler(value = BaseRuntimeException.class)
    public void baseExceptionHandler(BaseRuntimeException e, HttpServletResponse response)  throws IOException {
        response.setStatus(e.getStatus());
        log.error("BaseRuntimeException", e);
    }

    @ExceptionHandler(value = FeignException.class)
    public void feignException(FeignException e, HttpServletResponse response) throws IOException {
        if (e.getMessage().contains("auth_signin_required") || e.getMessage().contains("AUTH_SIGNIN_REQUIRED")) {
            response.setStatus(401);
        } else {
            response.setStatus(e.status());
        }
//        Result2 result2 = JsonUtil.readValue(e.getMessage().split("\n")[1], Result2.class);
//        if ("AUTH_SIGNIN_REQUIRED".equals(result2.getError())) {
//            response.setStatus(401);
//        } else {
//            response.setStatus(e.status());
//        }
        log.error("FeignException", e);
    }
}
